package com.abase.site.client.widget.body;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;

public class AbaseHomeBody extends Composite implements ValueChangeHandler<String> {

	private static AbaseHomeBodyUiBinder uiBinder = GWT
			.create(AbaseHomeBodyUiBinder.class);

	interface AbaseHomeBodyUiBinder extends UiBinder<FlowPanel, AbaseHomeBody> {
	}

	//
	  // UI Fields
	  //

	  //@UiField TYPE NAME;
	  @UiField DeckPanel deck;
	  @UiField FlowPanel left;
	  @UiField FlowPanel right;

	  private final Map<Collection<String>,Widget> widgetsByHistoryTokenPrefix = new HashMap<Collection<String>, Widget>();

	  public AbaseHomeBody() {
	    initWidget(uiBinder.createAndBindUi(this));

	    History.addValueChangeHandler(this);
	    redraw();
	  }

	  public void addToDeck(final Collection<String> tokenPrefixes, final Widget widget) {
	    this.deck.add(widget);
	    // Display the first widget if we just added it
	    if (1 == this.deck.getWidgetCount()) {
	      this.deck.showWidget(0);
	    }
	    this.widgetsByHistoryTokenPrefix.put(tokenPrefixes, widget);
	  }

	  /**
	   * @return the deck (center)
	   */
	  public DeckPanel getDeck() {
	    return this.deck;
	  }

	  /**
	   * @return the left column
	   */
	  public FlowPanel getLeft() {
	    return this.left;
	  }


	  /**
	   * @return the left column
	   */

	  public FlowPanel getRight() {
	    return this.right;
	  }

	  public void onValueChange(final ValueChangeEvent<String> event) {

	    final String token = event.getValue();

	    //
	    // Loop through the token prefixes, select the longest matching widget
	    //

	    int length = 0;
	    Widget widget = null;

	    for (final Collection<String> prefixes : this.widgetsByHistoryTokenPrefix.keySet()) {
	      for (final String prefix : prefixes) {
	        if (prefix.length() > length && token.startsWith(prefix)) {
	          length = prefix.length();
	          widget = this.widgetsByHistoryTokenPrefix.get(prefixes);
	        }
	      }
	    }

	    // Select the widget
	    if (null != widget) {
	      this.deck.showWidget(this.deck.getWidgetIndex(widget));
	    }
	  }

	  private void redraw() {

	  }

}
